package com.chilly.other.thread;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CyclicBarrier让一组线程全部达到一个状态之后再全部同时执行的效果。
 * 举个例子来验证CyclicBarrier可重用的效果：会议结束之后一起进入摸鱼状态，最后一天结束一起下班，这就是可重用。
 * Created by Chilly Cui on 2020/12/11.
 */
public class CyclicBarrierDemoMeetingReuse {
    private static int num = 4;
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(num, () -> {
        System.out.println("-------------------");
    });

    private static ExecutorService executorService = Executors.newFixedThreadPool(num);

    public static void main(String[] args) {
        executorService.submit(() -> {
            System.out.println("A在上厕所");
            try {
                Thread.sleep(4000);
                System.out.println("A上完了");
                cyclicBarrier.await();
                System.out.println("会议结束，A退出，开始撸代码");
                cyclicBarrier.await();
                System.out.println("A工作结束，下班回家");
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });
        executorService.submit(() -> {
            System.out.println("B在上厕所");
            try {
                Thread.sleep(2000);
                System.out.println("B上完了");
                cyclicBarrier.await();
                System.out.println("会议结束，B退出，开始摸鱼");
                cyclicBarrier.await();
                System.out.println("B摸鱼结束，下班回家");
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });
        executorService.submit(() -> {
            System.out.println("C在上厕所");
            try {
                Thread.sleep(3000);
                System.out.println("C上完了");
                cyclicBarrier.await();
                System.out.println("会议结束，C退出，开始摸鱼");
                cyclicBarrier.await();
                System.out.println("C摸鱼结束，下班回家");
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });

        executorService.submit(() -> {
            System.out.println("D在上厕所");
            try {
                Thread.sleep(1000);
                System.out.println("D上完了");
                cyclicBarrier.await();
                System.out.println("会议结束，D退出，开始摸鱼");
                cyclicBarrier.await();
                System.out.println("D摸鱼结束，下班回家");
                cyclicBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        });
        executorService.shutdown();
    }
}
